package com.sun.controller;

import com.sun.listener.event.MyEvent;
import com.sun.pojo.Student;
import com.sun.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private ApplicationContext applicationContext;

    @GetMapping("/get/student")
    public Student getStudent(@RequestParam Integer id){
        return studentService.queryStudentById(id);
    }

    @GetMapping("/redis/get/student")
    public Student getStudentByRedis(@RequestParam String key){
        return studentService.getStudentByRedis(key);
    }

    @GetMapping("/listener/get/studnet")
    public Student getStudentByListener(HttpServletRequest request){
        ServletContext servletContext = request.getServletContext();
        Object student = servletContext.getAttribute("student");
        return (Student) student;
    }

    @GetMapping("/listener/total")
    public String getTotalUser(HttpServletRequest request) {
        Integer count = (Integer) request.getSession().getServletContext().getAttribute("count");
        return "当前在线人数：" + count;
    }

    @GetMapping("/listener/total2")
    public String getTotalUser(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie;
        try {
            // 把 sessionId 记录在浏览器中
            cookie = new Cookie("JSESSIONID", URLEncoder.encode(request.getSession().getId(), "utf-8"));
            cookie.setPath("/");
            //设置 cookie 有效期为 2 天，设置长一点
            cookie.setMaxAge( 48*60 * 60);
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Integer count = (Integer) request.getSession().getServletContext().getAttribute("count");
        return "当前在线人数：" + count;
    }

    @GetMapping("/listener/request")
    public String getRequestInfo(HttpServletRequest request){
        System.out.println("requestListener中的初始化的name为："+request.getAttribute("name"));
        return "susses";
    }

    @GetMapping("/event/get")
    public Student eventgetRequestInfo(){
        Student student = studentService.eventGetStudent();
        MyEvent event = new MyEvent(this,student);
        applicationContext.publishEvent(event);
        return student;
    }

}
